package com.polukeuro.app.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;
import com.polukeuro.app.client.events.ConsummerLoadDataEvent;
import com.polukeuro.app.client.events.GroupHandler;
import com.polukeuro.app.client.events.NextGroupEvent;
import com.polukeuro.app.client.events.NotYetImplementedEvent;
import com.polukeuro.app.client.events.PreviousGroupEvent;
import com.polukeuro.app.client.jnsi.Group;
import com.polukeuro.app.client.jnsi.Team;
import com.polukeuro.app.client.manager.EventManager;
import com.polukeuro.app.utils.ServerPathsUtils;

public class GroupManagerWidget extends ConsummerWidget implements GroupHandler {

	private static final String JSON_URL = ServerPathsUtils.GROUPS_JSON_URI;

	private static GroupWidgetUiBinder uiBinder = GWT
			.create(GroupWidgetUiBinder.class);

	interface GroupWidgetUiBinder extends UiBinder<Widget, GroupManagerWidget> {
	}

	@UiField
	Button previousButton;

	@UiField
	Button nextButton;

	@UiField
	AbsolutePanel teamsContainer;

	public GroupManagerWidget() {
		initWidget(uiBinder.createAndBindUi(this));

		previousButton.setText("previous");
		nextButton.setText("next");

		previousButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				EventManager.getInstance().publish(new PreviousGroupEvent());
			}
		});

		nextButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				EventManager.getInstance().publish(new NextGroupEvent());
			}
		});
		
		this.needData(JSON_URL);
		
	}

	public void onPreviousGroupEvent(PreviousGroupEvent event) {
		EventManager.getInstance().publish(new NotYetImplementedEvent(event));
	}

	public void onNextGroupEvent(NextGroupEvent event) {
		EventManager.getInstance().publish(new NotYetImplementedEvent(event));
	}

	private void addGroup(Group group) {
		System.out.println("addGroup: " + group.getName());
		for (int i = 0; i < group.getTeams().length(); i++) {
			Team team = group.getTeams().get(i);
			TeamWidget tw = new TeamWidget(team);
			tw.addStyleName("team" + i);
			teamsContainer.add(tw);
		}

	}

	@Override
	public void setLoadData(ConsummerLoadDataEvent event) {
		JsArray<Group> jnsiGroups = JsonUtils.safeEval(event.getJson());
		for (int i = 0; i < jnsiGroups.length(); i++) {
			this.addGroup(jnsiGroups.get(i));
		}
	}

}
